package com.example.experiment4

import android.content.Intent
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.experiment4.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    private val editInfoLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) {
        // 修改信息界面返回后刷新展示
        bindPlayerInfo()
    }

    private val gameLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        // 游戏返回可能带回最新分数，刷新最佳分
        bindPlayerInfo()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        bindPlayerInfo()

        binding.btnEdit.setOnClickListener {
            val intent = Intent(this, EditInfoActivity::class.java)
            editInfoLauncher.launch(intent)
        }
        binding.btnStartGame.setOnClickListener {
            val intent = Intent(this, FlipGameActivity::class.java)
            gameLauncher.launch(intent)
        }
    }

    private fun bindPlayerInfo() {
        val info = PlayerRepository.getInfo()
        binding.tvName.text = if (info.name.isBlank()) getString(R.string.default_name) else info.name
        binding.tvPhone.text = if (info.phone.isBlank()) getString(R.string.default_phone) else info.phone
        binding.tvGender.text = when (info.gender) {
            Gender.MALE -> getString(R.string.gender_male)
            Gender.FEMALE -> getString(R.string.gender_female)
            Gender.UNKNOWN -> getString(R.string.gender_unknown)
        }
        binding.tvBest.text = info.bestScore.toString()
    }
}